import { defineStore } from "pinia";
import { ref } from "vue";
import router from "@/router";
import request from "@/utils/request";
import { userInfoService } from "@/api/user";
import { setToken, getToken, removeToken } from "@/utils/token";
import { asyncRoutes, constantRoutes, anyRoutes } from "@/router/constantRoutes";
import { cloneDeep } from "lodash";
let dynamicRoutes = []
const filterRoutes = (asyncRoutes, userRoutes) => {
    return asyncRoutes.filter((item) => {
        if (userRoutes.includes(item.name)) {
            if (item.children && item.children.length >= 1) {
                item.children = filterRoutes(item.children, userRoutes)
            }
            return true
        }
    })
}
const useUserStore = defineStore('User', () => {
    const token = ref(getToken())
    const name = ref('')
    const menuRoutes = ref(constantRoutes)

    //登录
    const login = async (data) => {
        const ans = await request({
            url: '/login',
            method: 'post',
            data
        })
        //code为1代表登录成功，返回成功的Promise
        if (ans.data.code == 1) {
            token.value = ans.data.data.token
            setToken(ans.data.data.token)
            console.log(getToken(), 'localtoken');

            return 'ok'
            //登录失败，返回失败的Promise
        } else {
            return Promise.reject(new Error(ans.data.msg))
        }
    }

    //获取用户信息
    const getUserInfo = async () => {
        const ans = await userInfoService()
        name.value = ans.data.data.name
        const Admin = ['Product', 'Attr', 'Spu']
        const userAsyncRoutes = filterRoutes(cloneDeep(asyncRoutes), Admin)
        menuRoutes.value = [...constantRoutes, ...userAsyncRoutes]
        dynamicRoutes = [...userAsyncRoutes, ...anyRoutes]
        dynamicRoutes.forEach((route) => {
            router.addRoute(route) // 动态添加路由
        })
        console.log(router.getRoutes());
        console.log();


    }
    //退出登录
    const logout = () => {
        token.value = ''
        name.value = ''
        removeToken()
        dynamicRoutes.map((route) => {
            router.removeRoute(route.name)
        })
    }

    return {
        token,
        name,
        menuRoutes,
        login,
        getUserInfo,
        logout
    }
})
export default useUserStore